<template>
  <div class="bgff">
    <div class="Pstate" v-if="productData.product_status !== 1">{{productData.product_status_text}}</div>
    <div class="product-collectionBtn" :class="{'red':productData.collected == 1}"
         @click.stop="collectionPorduct(productData.product_id,productData.collected,productData.collection_id)"><i
      class="iconfont icon-shoucang"></i></div>
    <swiper :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval" :duration="duration"
            :circular="circular" :style="{'height': bannerHeight + 'px'}">
      <div v-for="(img,index) in defaultSku.sku_images" :key="index">
        <swiper-item>
          <image :src="img+'?x-oss-process=image/resize,w_750,h_750/quality,Q_80/format,jpg'" class="slide-image"
                 mode="widthFix" @load="imageLoad"/>
        </swiper-item>
      </div>
    </swiper>

    <div class="product-title">
      <div class="productInfoDec">
        <h2 class="designerName">{{productData.designer_name}}</h2>
        <h3 class="productName">{{productData.product_name}}</h3>
        <p class="product_price">
          <del v-if="defaultSku.line_price">{{defaultSku.currency_logo}}{{defaultSku.line_price}}</del>
          <b :style="'color:#' + defaultSku.price_color">{{defaultSku.currency_logo}}{{defaultSku.show_price}}</b>
          <span class="labeltextOff">{{defaultSku.label_text}}</span>
        </p>
        <p class="rmbPrice" style="color: #a6a6a6">{{defaultSku.calculation_price_text}}</p>
      </div>
      <picker @change="PickerChange" :value="indexPicker" :range="sizeListText">
        <div class="product-size">
          <font>{{defaultSize}}</font>
          <i class="iconfont icon-zhankai"></i>
        </div>
      </picker>

    </div>

    <div class="product-block">
      <div class="product-blockTitle">商品信息</div>
      <div class="product-info">
        <p v-for="(dec,index) in defaultSku.sku_desc" :key="index">{{dec}}</p>
      </div>
    </div>

    <div class="product-brand" @click="isShowInstructions">
      <h2>购买须知</h2>
      <i class="iconfont" :class="{'icon-shouqi':showInstructions,'icon-zhankai':!showInstructions}"></i>
    </div>
    <div class="instructionsBox" v-show="showInstructions">
      <div class="instructions" v-for="(item,index) in productData.instructions" :key="index">
        <h2>{{item.title}}</h2>
        <img v-if="item.image" :src="item.image" mode="widthFix">
        <p v-if="item.content">{{item.content}}</p>
      </div>
    </div>

    <navigator :url="'../productList2/main?brandId='+ productData.designer_id + '&title='+ productData.designer_name">
      <div class="product-brand">
        <h2>{{productData.designer_name}}</h2>
        <i class="iconfont icon-zhankai"></i>
      </div>
    </navigator>

    <div class="product-contact">
      <dl>
        <button open-type="contact" @contact="handleContact"></button>
        <dt><i class="iconfont icon-kefu"></i> 在线客服</dt>
        <dd>9:00 - 18:00(工作日)</dd>
      </dl>

      <dl @click="tel">
        <dt><i class="iconfont icon-dianhuakefu"></i> 电话客服</dt>
        <dd>9:00 - 18:00(工作日)</dd>
      </dl>
    </div>
    <div class="posiHeight"></div>

    <div class="posiBottomBtn">
      <div class="BottomBtn disabled" v-if="productData.product_status == 0">商品已下架</div>
      <div style="display: flex;display: -webkit-flex; width:100%" v-else>
        <div class="BottomBtn">
          <picker @change="addCart" :value="indexPicker" :range="sizeListText">
            加入购物袋
          </picker>
        </div>
        <div class="BottomBtn">
          <picker @change="settlement" :value="indexPicker" :range="sizeListText">
            立即购买
          </picker>
        </div>
      </div>
    </div>
    <placeholder :show.sync="isPageEmpty" :message.sync="emptyMsg" :hidBtn="hidBtn" @tryAgain="onTap" :styleTop="0"/>
  </div>
</template>

<script>
  import {mapState, mapActions, mapMutations} from 'vuex'
  import {productDetailAction} from '@/store/funnames'
  import placeholder from '@/components/placeholder'
  import {getStorage} from '@/utils/wechat'

  export default {
    data() {
      return {
        productId: '',
        productData: {},
        defaultSku: [],
        indexPicker: 0,
        defaultSize: "选择尺码",
        sizeList: [],
        sizeListText: [],
        indicatorDots: true,
        autoplay: true,
        interval: 5000,
        duration: 900,
        circular: true,
        bannerHeight: 550,
        showInstructions: false,
        isFirst: true,
        isPageEmpty: false,
        hidBtn: false,
        emptyMsg: ''
      };
    },
    components: {
      placeholder
    },
    onLoad(e) {

    },
    onShow() {
      if (!this.isFirst) {
        if (!this.$wx.isArrayEmpty(this.productDetailList)) {
          this.productData = this.productDetailList[this.productDetailList.length - 1]
          console.log(this.productData, 'onShow')
          this.handlerProduct()
        }
      }
    },
    mounted() {
      console.log(this.$root.$mp.query, 1111)
      this.isFirst = true
      this.defaultSize = "选择尺码";
      this.sizeListText = [];
      this.productId = this.$root.$mp.query.productId;
      this.getdata()
      this.$root.$eventHub.$on('requestProductInfo', (target) => {
        this.getdata()
      });
    },
    onShareAppMessage(obj) {
      let pageParams = {
        path: '/pages/productDetails/main',
        params: {
          productId: this.productData.product_id
        }
      }
      return {
        title: this.productData.product_name,
        path: '/pages/index/main?pageParams=' + pageParams,
        message: this.productData.designer_name + ' ' + this.productData.product_name,
        imageUrl: this.productData.product_cover
      }
    },
    onUnload() {
      this.deleteProduct()
      this.sizeListText = []
    },
    computed: {
      // 计算属性的 getter
      ...mapState('cart', ['settleData']),
      ...mapState('productDetail', ['productDetailList'])
    },
    methods: {
      ...mapActions('cart', [
        'checkSettle',
        'getCarts'
      ]),
      ...mapMutations('productDetail', {
        addProduct: productDetailAction.ACTION_PRODUCT_DETAIL_ADD,
        deleteProduct: productDetailAction.ACTION_PRODUCT_DETAIL_DELETE
      }),
      onTap() {
        this.getdata()
      },
      isShowInstructions() {
        this.showInstructions = !this.showInstructions
      },
      imageLoad: function (e) {
        var res = wx.getSystemInfoSync()
        var imgwidth = e.mp.detail.width,
          imgheight = e.mp.detail.height,
          ratio = imgwidth / imgheight
        this.bannerHeight = res.windowWidth / ratio
      }
      ,
      async getdata() {
        const data = await this.$fly.post(this.$url.URL_PRODUCTDETAILS, {
          product_id: this.productId
        })
        if (data.successCode === 1) {
          this.isFirst = false
          if (this.$wx.isArrayEmpty(data.data)) {
            this.isPageEmpty = true
            this.hidBtn = false
            this.emptyMsg = "商品已下架或不存在"
          } else {
            this.isPageEmpty = false
            this.productData = data.data;
            this.addProduct(this.productData)
            this.handlerProduct()
          }
        } else {
          this.isPageEmpty = true
          this.hidBtn = false
          this.emptyMsg = data.message
        }
      },
      handlerProduct() {
        this.$wx.setTitleBarTitle(this.productData.product_name);
        this.defaultSku = this.productData.skus[0].xSizes[0];
        this.sizeList = this.productData.skus[0].xSizes;
        for (let i = 0; i < this.sizeList.length; i++) {
          this.sizeListText.push(this.sizeList[i].size)
        }
      }
      ,
      //选择尺码
      PickerChange(e) {
        this.defaultSize = this.productData.skus[0].xSizes[e.mp.detail.value].size;
        this.defaultSku = this.productData.skus[0].xSizes[e.mp.detail.value];
        this.indexPicker = e.mp.detail.value;
      }
      ,
      tel: function () {
        wx.makePhoneCall({
          phoneNumber: "4008877993"
        });
      }
      ,
      handleContact(e) {
        console.log(e.path);
        console.log(e.query);
      }
      ,
      //加入购物袋
      async addCart(e) {
        if (!this.$wx.isLogin()) {
          this.$wx.jumper("../login/main");
          return
        }
        this.PickerChange(e)
        const data = await
          this.$fly.post(this.$url.URL_ADDCART, {
            product_id: this.defaultSku.product_id,
            product_sku_id: this.defaultSku.product_sku_id,
            product_price: this.defaultSku.show_price,
            product_qty: 1,
          })
        if (data.successCode === 1) {
          this.getCarts()
          this.$wx.showLongToast('已加入购物袋')
        } else {

        }
      }
      ,
      //去收银台
      async settlement(e) {
        if (!this.$wx.isLogin()) {
          this.$wx.jumper("../login/main");
          return
        }
        this.PickerChange(e)
        var productItem = [{
          product_id: this.defaultSku.product_id.toString(),
          product_sku_id: this.defaultSku.product_sku_id.toString(),
          product_qty: this.defaultSku.product_sku_quantity.toString()
        }]
        console.log(productItem)
        await
          this.checkSettle({isSettlePage: false, checkedProduct: productItem})
        if (this.settleData) {
          this.$wx.jumper('/pages/cashier/main')
        } else {
          this.$wx.showShortToast(this.errorMsg)
        }
      }
      ,
      collectionPorduct(id, iscollected, collectedId) {
        const self = this
        if (this.$wx.isLogin()) {
          if (iscollected == 0) {
            this.getcollectionPorduct(id)
          } else {
            this.removeCollectionPorduct(id, collectedId)
          }
        } else {
          wx.showModal({
            title: '提示',
            content: '您还没有登录，去登录?',
            success(res) {
              self.$wx.jumper("../login/main");
            }
          })
        }
      }
      ,
      async getcollectionPorduct(id) {
        const data = await
          this.$fly.post(this.$url.URL_ADDCOLLECTIONPRODUCT, {
            product_id: id
          })
        if (data.successCode === 1) {
          this.$wx.showLongToast('收藏成功！')
          this.productData.collected = 1
          this.$root.$eventHub.$emit('requestGoods', true)  //更新商品列表
          this.$root.$eventHub.$emit('requestGoods2', true)  //更新商品列表
        }
      }
      ,
      async removeCollectionPorduct(id, collectedId) {
        const data = await
          this.$fly.post(this.$url.URL_REMOVECOLLECTIONPRODUCT, {
            collection_id: collectedId
          })
        if (data.successCode === 1) {
          this.$wx.showLongToast('取消成功！')
          this.productData.collected = 0
          this.$root.$eventHub.$emit('requestGoods', true)  //更新商品列表
          this.$root.$eventHub.$emit('requestGoods2', true)  //更新商品列表
        }
      }
    }
  }
  ;
</script>

<style scoped>
  .slide-image {
    width: 100%;
    height: 100%;
  }
</style>
